package com.xufx.thread.liaoxuefeng.thread20_singleton;

/**
 * 要想实现单例模式，volatile和synchronized都是必须的
 * volatile保证执行的代码不被重排
 * synchronized保证互斥，不会让让两个线程同时创建了对象
 */
public class Singleton {

    private volatile static Singleton singleton;

    public Singleton() {
    }

    private static Singleton createSingleton() {
        if (null == singleton) {
            synchronized (Singleton.class) {
                if (null == singleton) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(Singleton::createSingleton);
        Thread t2 = new Thread(Singleton::createSingleton);
        t1.start();
        t2.start();
    }
}
